#include <stdio.h>
#include "Nano100Series.h"
#include "Common.h"
#include "UsbTransfer.h"

void SystemCoreInit(void)
{
    SYS_UnlockReg();

    /* 12MHz HXT, HCLK from PLL */ 
    CLK_EnableXtalRC(CLK_PWRCTL_HXT_EN_Msk);
    CLK_EnablePLL(CLK_PLLCTL_PLL_SRC_HXT, 96000000);
    CLK_WaitClockReady(CLK_CLKSTATUS_HXT_STB_Msk | CLK_CLKSTATUS_PLL_STB_Msk);
    CLK_SetHCLK(CLK_CLKSEL0_HCLK_S_PLL, CLK_HCLK_CLK_DIVIDER(3));

    /* to calculate PllClock, SystemCoreClock and CycylesPerUs automatically. */
    SystemCoreClockUpdate();
		
    SYS_LockReg();
}

void SystemPeripheralInit(void)
{
	SYS_UnlockReg();

	/* UART0 : Debug */
	CLK_SetModuleClock(UART0_MODULE, CLK_CLKSEL1_UART_S_HXT, CLK_UART_CLK_DIVIDER(1));
	CLK_EnableModuleClock(UART0_MODULE);
	SYS->PB_L_MFP &= ~(SYS_PB_L_MFP_PB0_MFP_Msk | SYS_PB_L_MFP_PB1_MFP_Msk);
    SYS->PB_L_MFP |= (SYS_PB_L_MFP_PB0_MFP_UART0_RX | SYS_PB_L_MFP_PB1_MFP_UART0_TX);

	/* USB */
	CLK_SetModuleClock(USBD_MODULE, 0, CLK_USB_CLK_DIVIDER(2));
    CLK_EnableModuleClock(USBD_MODULE);

	SYS_LockReg();
}

int main(void)
{
	SystemCoreInit();
	SystemPeripheralInit();

	UART_Open(UART0, 115200);
	LogDebug("\nD1 ISP power on ...\n");

	UsbTransferInit();
	UsbTransferStart();

	while (1) {
		UsbTransferHandleEvent();
	}
}
